
function socketInit() {
  const http = require("http");
  const {Server} = require("socket.io");
  var app = require('./app');
  // 创建http服务器
  const httpServer = http.createServer(app);
  // 实例化socket.io
  const io = new Server(httpServer, {
    transports: ["websocket"]
  });
  const {formatDate} = require('./utils/utils')
  // 监听客户端连接
  const users = {}
  io.on('connection', (socket) => {
    //socket 对象就是 建立连接的会话对象
    //监听client客户端emit的message事件
    console.log('连接已经建立', `id:${socket.id}`,users)
    //1.输入昵称加入群聊
    socket.on('login', (nikname) => {
      console.log('输入昵称加入群聊', `nikname:${nikname}`)
      if (users[nikname]) {
        //如果昵称已存在 触发repeat告知客户端昵称冲突
        socket.emit('logged_status', 0)
        return
      }
      socket.nikname = nikname
      users[nikname] = {
        name: nikname,
        socket: socket,
        loginTime: formatDate()
      }
      //登录成功,广播,登陆者昵称
      console.log('登陆成功_nikname：', nikname)
      //发送给全部群聊者，登陆信息
      io.emit('logged', nikname)
      socket.emit('logged_status', 1)
    })
    //2.客户端发过来的信息
    socket.on('send', (msg) => {
      let msgTime = formatDate()
      //发送给除了发送者的所有用户
      console.log('msg:', msg)
      socket.broadcast.emit('chat', {
        nikname: socket.nikname,
        msg: msg,
        time: msgTime
      })
    })
    //3.客户端断开连接
    socket.on('disconnect', () => {
      let nikname = socket?.nikname
      if (nikname && users[nikname]) {
        delete users[nikname]
        //发送给全部群聊者，退出信息
        io.emit('logout', nikname)
      }
    })
  })

  const PORT = process.env.SOCKET_PORT || 8787;
  httpServer.listen(PORT, () => {
    console.log(`socket Server running on port ${PORT}`);
  });
}

module.exports = socketInit; // 导出服务器实例
